package com.shensi.adminCollect.controller.station;

import com.github.pagehelper.PageHelper;
import com.shensi.adminCollect.common.constant.HttpStatus;
import com.shensi.adminCollect.common.constant.UserConstants;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.ResultData;
import com.shensi.common.core.page.PageDomain;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.common.core.page.TableSupport;
import com.shensi.common.redis.service.RedisCache;
import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.customer.CustomerCardUseRecord;
import com.shensi.adminCollect.service.customer.ICustomerCardUseRecordService;
import com.shensi.adminCollect.service.customer.ICustomerElectronicCardService;
import com.shensi.adminCollect.service.integral.ICustomerPointsRecordService;
import com.shensi.adminCollect.domain.station.*;
import com.shensi.adminCollect.domain.station.dto.CardClassSettDto;
import com.shensi.adminCollect.enums.station.PrintEnum;
import com.shensi.adminCollect.mapper.station.OilMapper;
import com.shensi.adminCollect.mapper.station.PresentAmountRecordMapper;
import com.shensi.adminCollect.service.station.*;
import com.shensi.adminCollect.utils.station.FeiEPrinterUtil;
import com.shensi.adminCollect.utils.station.StaffUtil;
import com.shensi.adminCollect.utils.station.YiLianYunPrinterUtil;
import com.shensi.adminCollect.domain.system.XcxActualPaymentDto;
import com.shensi.adminCollect.service.system.IAppUserInfoUserService;
import com.shensi.adminCollect.service.system.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;
/**
 * 订单支付Controller
 *
 * @author qujia
 * @date 2020-12-10
 */
@RestController
@RequestMapping("/station/historyOrder")
@Api(tags = "历史订单相关接口", description = "历史订单相关接口")
public class PayOrderHistoryController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(PayOrderHistoryController.class);
    @Autowired
    private IPayOrderHistoryService payOrderHistoryService;

    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ClassSettlementCardService classSettlementCardService;
    @Autowired
    private IClassSettlementService classSettlementService;
    @Autowired
    private IStationService stationService;

    @Autowired
    private IStationDeviceManageService stationDeviceManageService;

    @Autowired
    private RedisCache redisCache;

    @Resource
    private IAppUserInfoUserService appUserInfoUserService;

    @Resource
    private ICustomerElectronicCardService customerElectronicCardService;

    @Resource
    private ICustomerPointsRecordService customerPointsRecordService;

    @Resource
    private IEnterpriseService enterpriseService;

    @Resource
    private ICustomerCardUseRecordService customerCardUseRecordService;

    @Resource
    private PayOrderController payOrderController;

    @Resource
    private OilMapper oilMapper;

    @Resource
    private PresentAmountRecordMapper presentAmountRecordMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${qujia.payBaseUrl}")
    private String payBaseUrl;


    @GetMapping("/feiePush")
    @ApiOperation("补打票")
    public AjaxResult feiePush(PayOrder payOrder1) { //
        try {
            boolean his = false;
            PayOrder payOrder = payOrderService.selectPayOrderForFeiEById(payOrder1.getOrderId());
            if(payOrder == null){
                payOrder = payOrderHistoryService.selectPayOrderForFeiEById(payOrder1.getOrderId());
                his = true;
            }
            log.info("订单信息{}",payOrder);
            StationDeviceManage stationDeviceManage = new StationDeviceManage();
            stationDeviceManage.setStationId(payOrder.getStationId());
            stationDeviceManage.setDeviceType("3");
            List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
            log.info("小票机信息{}",stationDeviceManages);
            if (stationDeviceManages == null || stationDeviceManages.size() <= 0) {
                return AjaxResult.error("当前站点没有打印机");
            }



            //加油员ID
            String oilPersonnelId = payOrder.getOilPersonnelId();

            StationDeviceManage stationDeviceManagerRes;
            try {
                //筛选绑定了用户的小票机
                List<StationDeviceManage> manageWithUser = new ArrayList<>();
                if(payOrder!=null&&payOrder.getOilPersonnelId()!=null&&!"".equals(payOrder.getOilPersonnelId())){
                    manageWithUser = stationDeviceManages.stream().filter(device -> {
                        if(StringUtils.isNotBlank(device.getUserIds())){
                            List<String> userIdsList = Arrays.asList(device.getUserIds().split(","));
                            return userIdsList.contains(oilPersonnelId);
                        }
                        return false;
                    }).collect(Collectors.toList());
                }
                stationDeviceManagerRes  = CollectionUtils.isNotEmpty(manageWithUser) ? manageWithUser.get(0) : stationDeviceManages.get(0);
                log.info("筛选绑定用户的小票机信息：{}",stationDeviceManagerRes);
            }catch (Exception e){
                stationDeviceManagerRes = stationDeviceManages.get(0);
                log.error(e.getMessage());
            }

            String audio = stationDeviceManagerRes.getAudio();
            log.info("自定义语音audio:{}",audio);

            log.info("最终小票机信息：{}",stationDeviceManagerRes);
            String deviceFactory = stationDeviceManagerRes.getDeviceFactory();
            PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);

            //StringBuilder content = new StringBuilder();
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            ResultData resultData = restTemplate.getForObject(payBaseUrl+"/receiptSection/getOrderReceiptString?orderNo={1}&deviceFactory={2}&printType={3}&his={4}", ResultData.class,
                    payOrder.getOrderNo(),deviceFactory,stationDeviceManages.get(0).getPrintType(),his);
            if (resultData.getCode() != 0) {
                throw new CustomException(resultData.getMsg());
            }
            String receiptStr = (String) resultData.getData();
            Oil oil = oilMapper.selectOilByName(payOrder.getOilName());

            AjaxResult ajaxResult = AjaxResult.success();
            switch (printEnum){
                case YILIANYUNK4:
                    if (oil != null) {
                        payOrder.setOilName(oil.getOilId().toString());
                    }
                    ajaxResult = YiLianYunPrinterUtil.print(receiptStr, stationDeviceManagerRes, payOrder);
                    break;
                case YILIANYUN:
//
//                    HashMap<String, String> audioMap = new HashMap<>();
//                    audioMap.put("手机尾号", Objects.isNull(payOrder.getCustomerPhone()) ? "" : payOrder.getCustomerPhone().substring(7,11));
//                    audioMap.put("加油金额", payOrder.getReceivableAmt().toString() + "元");
//                    audioMap.put("支付金额", payOrder.getAmt().toString() + "元");
//                    audioMap.put("枪号", payOrder.getOilGun() + ",");
//                    audioMap.put("油品", payOrder.getOilName().replace("#","号") + ",");
//
//                    StringBuffer sb = new StringBuffer();
//                    try {
//                        String[] split = audio.split(";");
//
//                        //加油语音
//                        String oilOrderAudio = split[0];
//                        List<String> oilOrderAudioList = Arrays.asList(oilOrderAudio.split(","));
//                        sb.append("<audio>");
//                        for (String audioContent : oilOrderAudioList) {
//                            sb.append(audioContent + audioMap.get(audioContent));
//                        }
//                        sb.append("</audio>");
//                        log.info("播报语音：{}",sb);
//                    }catch (Exception e){
//                        sb = new StringBuffer("<audio>手机尾号").append(payOrder.getMobilePhone().substring(7, 11)).append("支付金额").append(payOrder.getAmt())
//                                .append("元").append("加油金额").append(payOrder.getReceivableAmt()).append("元").append(payOrder.getOilGun()).append("号油枪").append(payOrder.getOilName()).append("号油,</audio>");
//                    }
//
//                    String ylyContent = content.toString().replace("<BR>", "\r\n").replace("</B></BOLD>","</center></FS2> ").replace("<BOLD><B>","<FS2><center>");
//                    StringBuffer finalContent = sb.append(ylyContent);
//
//                    //初始化控制器类
//                    Methods m= Methods.getInstance();
//                    Object token = redisCache.getCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId());
//
//                    Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
//
//                    if(Objects.nonNull(token)){
//                        String print = m.print(stationDeviceManagerRes.getDeviceNo(),finalContent.toString(),random6.toString());
//                        log.info("小票机返回值{}",print);
//                        org.json.JSONObject json = new JSONObject(print);
//                        if("0".equals(json.getString("error"))){
//                            break;
//                        }
//                    }
//
//                    //初始化终端信息
//                    m.init(stationDeviceManagerRes.getClientId(), stationDeviceManagerRes.getClientSecret());
//                    //获取token
//                    String refreshToken = m.getFreedomToken();
//                    //存入redis
//                    redisCache.setCacheObject("STATION:DEVICE:" + stationDeviceManagerRes.getClientId(),refreshToken,30, TimeUnit.DAYS);
//
//
//                    String print = m.print(stationDeviceManagerRes.getDeviceNo(), finalContent.toString(), random6.toString());
                    if (oil != null) {
                        payOrder.setOilName(oil.getOilId().toString());
                    }
                    ajaxResult = YiLianYunPrinterUtil.print(receiptStr, stationDeviceManagerRes, payOrder);
                    break;

                case FEIE:

                    String result = FeiEPrinterUtil.printReceipt(stationDeviceManages.get(0).getDeviceNo(), receiptStr);
                    org.json.JSONObject resJson = new org.json.JSONObject(result);
                    if("ok".equals(resJson.get("msg"))){
                        ajaxResult = AjaxResult.success("补打小票成功");
                    }else {
                        ajaxResult = AjaxResult.success("补打小票失败");

                    }
                    break;
                default:
                    log.info("没有配置小票机，打印失败");
                    break;
//            return AjaxResult.success("打印成功");
            }
            int i=(int)ajaxResult.get("code");
            if (i==200){
                payOrderService.updatePayOrderPrintStatus(payOrder.getOrderNo());
            }

            return ajaxResult;
        }catch (Exception e){
            logger.error(">pushConsumeToUser", e);
            return AjaxResult.error(e.getMessage());

        }
//        return AjaxResult.success("打印成功");
    }

    private String getElectronicCardAmt(PayOrder payOrder){
//        Enterprise enterprise = enterpriseService.selectEnterpriseById(payOrder.getEnterpriseId());
//        String cardUseRangeFlag = enterprise.getCardUseRangeFlag();
//
//        SysAppUserInfoUser sysAppUserInfoUser = appUserInfoUserService.selectAppUserInfoById(Long.valueOf(payOrder.getConsumerId()));
//        log.info("用户信息{}",sysAppUserInfoUser.toString());
//        CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
//        customerElectronicCard.setCustomerNo(sysAppUserInfoUser.getMemberCode());
//
//        if("1".equals(cardUseRangeFlag)){
//            customerElectronicCard.setStationId(payOrder.getEnterpriseId());
//        }else if("2".equals(cardUseRangeFlag)){
//            customerElectronicCard.setStationId2(payOrder.getStationId());
//        }
//
//        String cardOilType =  "汽油".equals(payOrder.getOrderType()) ? "1" : "2";
//        customerElectronicCard.setCardOilsType(cardOilType);
//        log.info("customerElectronicCard:{}",customerElectronicCard);
//        CustomerElectronicCard electronicCardInfo =  customerElectronicCardService.getElectronicCardInfo(customerElectronicCard);
//        log.info("电子卡信息：{}",electronicCardInfo.toString());
        CustomerCardUseRecord customerCardUseRecord = customerCardUseRecordService.selectCustomerCardUseRecordByOrderNo(payOrder.getOrderNo());
        return Objects.nonNull(customerCardUseRecord) ? customerCardUseRecord.getBalance().toString() : "0";
    }

    /**
     * 查询订单支付列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        if (payOrder.getBeginTime() != "" && payOrder.getEndTime() != "") {
// 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate beginDate = LocalDate.parse(payOrder.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(payOrder.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                List<PayOrder> betweenTime = new ArrayList<>();
                TableDataInfo rspData = new TableDataInfo();
                rspData.setCode(HttpStatus.ERROR);
                rspData.setMsg("仅可查询一个月");
                rspData.setRows(betweenTime);
                rspData.setTotal((long) 0);
                return rspData;
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate today = LocalDate.now(); // 当前日期
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            payOrder.setBeginTime(beginTimeStr);
            payOrder.setEndTime(endTimeStr);
        }
        log.info("list是否传了isDeleted:{}",payOrder.getIsDeleted());
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        if (StringUtils.equals(UserConstants.LEVEL_TWO,user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (CollectionUtils.isNotEmpty(list)) {
                payOrder.setStationIdList(list);
            }

        } else if (StringUtils.equals(UserConstants.LEVEL_THREE,user.getUserLevel())) {
            payOrder.setStationId(user.getStationId());

            if(StaffUtil.isStaff(user)){
                payOrder.setOilPersonnelId(String.valueOf(user.getUserId()));
            }else{
                Station station = stationService.selectStationById(current.getUser().getStationId());
                String showPayWayIds =  station.getShowPayWayIds();
                if (showPayWayIds!=null && payOrder.getIsReport()==null){
                    String[] idArray = showPayWayIds.split(","); // 拆分成字符串数组
                    List<Long> idList = new ArrayList<>();
                    for (int i = 0; i < idArray.length; i++) {
                        String id = idArray[i].trim();
                        if (!id.isEmpty()) {
                            idList.add(Long.parseLong(id));
                        }
                    }
                    payOrder.setPayWayIdList(idList);
                }
            }
        }
        payOrderController.assignPayOrder(payOrder,current.getUser());
        log.info("油站id：{}",payOrder.getStationIdList());
        startPage();
        // 查询七天内数据表的总记录数
        int within7DaysTotalCount = payOrderService.getStatusCount(payOrder);
        // 查询七天外数据表的总记录数
        int beyond7DaysTotalCount = payOrderHistoryService.getStatusCount(payOrder);
        // 计算总页数和每页的数据量
        int totalCount = within7DaysTotalCount + beyond7DaysTotalCount;
        PageDomain pageDomain = TableSupport.buildPageRequest();

        int totalPages = (int) Math.ceil((double) totalCount / pageDomain.getPageSize());
        int offset = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();
        int limit = pageDomain.getPageSize();
// 针对七天内数据表执行分页查询


        List<PayOrder> mergedData = new ArrayList<>();
        if (offset < within7DaysTotalCount) {
            PageHelper.offsetPage(offset, limit);
            List<PayOrder> within7DaysData = payOrderService.selectPayOrderAndWithdrawalAmountList(payOrder);
            mergedData.addAll(within7DaysData);
        }
//        List<PayOrder> beyond7DaysData = payOrderHistoryService.selectPayOrderList(payOrder);
        if (offset >= within7DaysTotalCount) {
            // 针对七天外数据表执行分页查询
            int beyond7DaysOffset = Math.max(0, offset - within7DaysTotalCount);
            int beyond7DaysLimit = limit;
            PageHelper.offsetPage(beyond7DaysOffset, beyond7DaysLimit);
            List<PayOrder> beyond7DaysData = payOrderHistoryService.selectPayOrderAndWithdrawalAmountList(payOrder);
            mergedData.addAll(beyond7DaysData);
        } else if (offset < within7DaysTotalCount && offset + limit > within7DaysTotalCount) {
            // 针对七天外数据表执行分页查询
            int beyond7DaysOffset = Math.max(0, offset - within7DaysTotalCount);
            int beyond7DaysLimit = limit + offset - within7DaysTotalCount;
            PageHelper.offsetPage(beyond7DaysOffset, beyond7DaysLimit);
            List<PayOrder> beyond7DaysData = payOrderHistoryService.selectPayOrderAndWithdrawalAmountList(payOrder);
            mergedData.addAll(beyond7DaysData);
        }
        // 按照需要进行排序

        // 返回分页数据

        //payOrder.setStatus("1");
//        List<PayOrder> payOrderList = payOrderHistoryService.selectPayOrderList(payOrder);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(mergedData);
        rspData.setTotal((long) totalCount);
        return rspData;
//        return getDataTable();
    }

    /**
     * 查询所有订单包括未支付的
     */
    @GetMapping("/allList")
    public TableDataInfo allList(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        startPage();
        List<PayOrder> payOrderList = payOrderHistoryService.selectAllPayOrderList(payOrder);
        return getDataTable(payOrderList);
    }


    @GetMapping("/selectPayOrderList")
    public TableDataInfo selectPayOrderList(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        startPage();
        //payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderHistoryService.selectPayOrderList(payOrder);
        return getDataTable(payOrderList);
    }


    /**
     * 关联用户查询订单支付列表
     */
    @GetMapping("/selectUserPayOrderList")
    public TableDataInfo selectUserPayOrderList(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        startPage();
        //payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderHistoryService.selectUserPayOrderList(payOrder);
        return getDataTable(payOrderList);
    }


    /**
     * 查询订单，通过appuser 信息
     */
    @GetMapping("/selectPayOrderByAppUserInfo")
    public TableDataInfo selectPayOrderByAppUserInfo(SysAppUserInfo sysAppUserInfo) {
        startPage();
        LoginUser current = SecurityUtils.getLoginUser();
        PayOrder payOrder = new PayOrder();

        List<String> stationids = new ArrayList<>();
        if ("0".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(sysAppUserInfo.getStationId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station station1 : stations) {
                stationids.add(station1.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(stationids);
            }
        } else if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station station1 : stations) {
                stationids.add(station1.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(stationids);
            }
        } else if ("2".equals(current.getUser().getUserLevel())) {
            stationids.add(current.getUser().getStationId() + "");

        }

        payOrder.setConsumerId(sysAppUserInfo.getUserId());
        // payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderHistoryService.selectPayOrderList(payOrder);
        return getDataTable(payOrderList);
    }

    /**
     * 查询订单支付列表
     */
    @GetMapping("/listInfo")
    public TableDataInfo listInfo(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setOrderType("1");
        //payOrder.setStatus("1");
        List<PayOrder> payOrderList = payOrderHistoryService.selectPayOrderList(payOrder);
        return getTable(payOrderList);
    }

    /**
     * 查询总金额，总升数
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/selectDaySources")
    public AjaxResult selectDaySources(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderHistoryService.selectDaySources(payOrder);
        return AjaxResult.success(order);
    }


    /**
     * 查询总金额，总升数(针对加气平台的)
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/selectLNGDaySources")
    public AjaxResult selectLNGDaySources(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderHistoryService.selectDaySources(payOrder);
        return AjaxResult.success(order);
    }

    /**
     * 查询总站下的合计数
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/selectAllDaySources")
    public AjaxResult selectAllDaySources(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
            // 员工
            if(StaffUtil.isStaff(current.getUser())){
                payOrder.setOilPersonnelId(String.valueOf(current.getUser().getUserId()));
            }
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderHistoryService.selectAllDaySources(payOrder);
        PayOrder newPayOrder = payOrderService.selectAllDaySources(payOrder);
        PayOrder result = getResult(order,newPayOrder);
        return AjaxResult.success(result);
    }

    /**数据组装*/
    private PayOrder getResult(PayOrder order,PayOrder newPayOrder){
        PayOrder result = new PayOrder();
        result.setAmt(addBigdecimal(order.getAmt(),newPayOrder.getAmt()));
        result.setCountNum(order.getCountNum() + order.getCountNum());
        result.setCyAmt(addBigdecimal(order.getCyAmt(),newPayOrder.getCyAmt()));
        result.setOrderLiters(addBigdecimal(order.getOrderLiters(),newPayOrder.getOrderLiters()));
        result.setQyAmt(addBigdecimal(order.getQyAmt(),newPayOrder.getQyAmt()));
        result.setTotalWithdrawalAmount(addBigdecimal(order.getTotalWithdrawalAmount(),newPayOrder.getTotalWithdrawalAmount()));
        return result;
    }

    private BigDecimal addBigdecimal(BigDecimal first,BigDecimal second){
        if(Objects.nonNull(first) && Objects.nonNull(second)){
            return first.add(second);
        } else if(Objects.isNull(first) && Objects.nonNull(second)){
            return second;
        } else {
            return first;
        }
    }

    /**
     * 查询总金额，总升数
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/selectSumPayOrder")
    public AjaxResult selectSumPayOrder(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderHistoryService.selectDaySources(payOrder);
        return AjaxResult.success(order);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/selectOilTypeSources")
    public TableDataInfo selectOilTypeSources(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.selectOilTypeSources(payOrder);
        return getTable(orderList);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数，查询所有订单信息
     * @param payOrder
     * @return
     */
    @GetMapping("/selectAllOilTypeSources")
    public TableDataInfo selectAllOilTypeSources(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        // payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.selectAllOilTypeSources(payOrder);
        return getTable(orderList);
    }


    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/dayOilTypeSources")
    public TableDataInfo dayOilTypeSources(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.dayOilTypeSources(payOrder);
        return getTable(orderList);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/dayAllOilTypeSources")
    public TableDataInfo dayAllOilTypeSources(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.dayAllOilTypeSources(payOrder);
        return getTable(orderList);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/selectOverViewData")
    public AjaxResult selectOverViewData(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderHistoryService.selectOverViewData(payOrder);
        return AjaxResult.success(order);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数(包括已经退款的)
     * @param payOrder
     * @return
     */
    @GetMapping("/selectAllOverViewData")
    public AjaxResult selectAllOverViewData(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        PayOrder order = payOrderHistoryService.selectAllOverViewData(payOrder);
        return AjaxResult.success(order);
    }

    /**
     * 月报数据详细
     */
    @GetMapping("/selectDayReportDetail")
    public TableDataInfo selectDayReportDetail(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        //默认当前登陆人的ID 5冯总油站
        startPage();
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.selectDayReport(payOrder);
        return getDataTable(orderList);
    }

    /**
     * 月报数据详细
     */
    @GetMapping("/selectAllDayReportDetail")
    public TableDataInfo selectAllDayReportDetail(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
            // 员工
            if(StaffUtil.isStaff(current.getUser())){
                payOrder.setOilPersonnelId(String.valueOf(current.getUser().getUserId()));
            }
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        }
        //默认当前登陆人的ID 5冯总油站
        startPage();
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderService.selectNewAllDayReport(payOrder);
        return getDataTable(orderList);
    }

    /***
     * 根据油品分类，查询油品的总金额，总升数
     * @param payOrder
     * @return
     */
    @GetMapping("/selectDayReport")
    public TableDataInfo selectDayReport(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.selectDayReport(payOrder);
        return getTable(orderList);
    }

    /**
     * 导出订单支付列表
     */
    @GetMapping("/export")
    @ApiOperation("订单导出")
    public AjaxResult export(PayOrder payOrder) {
        /*List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        if (payOrder.getBeginTime() != null && payOrder.getEndTime() != null) {
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate beginDate = LocalDate.parse(payOrder.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(payOrder.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                return AjaxResult.error("仅可查询一个月");
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate today = LocalDate.now(); // 当前日期
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            payOrder.setBeginTime(beginTimeStr);
            payOrder.setEndTime(endTimeStr);
        }
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
            Station station = stationService.selectStationById(current.getUser().getStationId());
            String showPayWayIds =  station.getShowPayWayIds();
            if (showPayWayIds!=null){
                String[] idArray = showPayWayIds.split(","); // 拆分成字符串数组
                List<Long> idList = new ArrayList<>();
                for (int i = 0; i < idArray.length; i++) {
                    String id = idArray[i].trim();
                    if (!id.isEmpty()) {
                        idList.add(Long.parseLong(id));
                    }
                }
                payOrder.setPayWayIdList(idList);
            }
        }
//        else {
//            Station station = new Station();
//            List<Station> stations = stationService.selectStationList(station);
//            for (Station ss : stations) {
//                list.add(ss.getStationId() + "");
//            }
//            if (stations != null && stations.size() > 0) {
//                payOrder.setStationIdList(list);
//            }
//
//        }
        payOrderController.assignPayOrder(payOrder,current.getUser());
        List<PayOrder> payOrderListInSeven = payOrderService.selectPayOrderList(payOrder);
        List<PayOrder> payOrderList = payOrderHistoryService.selectPayOrderList(payOrder);
//        List<PayOrder> payOrderListInSeven = payOrderService.selectPayOrderExport(payOrder);
//        List<PayOrder> payOrderList = payOrderHistoryService.selectPayOrderExport(payOrder);
        payOrderListInSeven.addAll(payOrderList);
        ExcelUtil<PayOrder> util = new ExcelUtil<PayOrder>(PayOrder.class);
        return util.exportExcel(payOrderListInSeven, "order");
    }


    /**
     * 经营报表订单导出
     */
    @GetMapping("/exportByDay")
    @ApiOperation("经营报表订单导出")
    public AjaxResult exportByDay(PayOrder payOrder) {
        if (payOrder.getBeginTime() != null && payOrder.getEndTime() != null) {
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate beginDate = LocalDate.parse(payOrder.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(payOrder.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                return AjaxResult.error("仅可查询一个月");
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate today = LocalDate.now(); // 当前日期
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            payOrder.setBeginTime(beginTimeStr);
            payOrder.setEndTime(endTimeStr);
        }
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        }
        payOrderController.assignPayOrder(payOrder,current.getUser());
        List<PayOrder> payOrderListInSeven = payOrderService.selectPayOrderList(payOrder);
        List<PayOrder> payOrderList = payOrderHistoryService.selectPayOrderList(payOrder);
        payOrderListInSeven.addAll(payOrderList);
        ExcelUtil<PayOrder> util = new ExcelUtil<PayOrder>(PayOrder.class);
        return util.exportExcel(payOrderListInSeven, "order");
    }


    /**
     * 获取订单支付详细信息
     */
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId) {
        return AjaxResult.success(payOrderHistoryService.selectPayOrderById(orderId));
    }


    /**
     * 获取92号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata92")
    public TableDataInfo listQydata92(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        payOrder.setOilName("92#");
        payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取95号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata95")
    public TableDataInfo listQydata95(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        payOrder.setOilName("95#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取97号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata98")
    public TableDataInfo listQydata98(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        payOrder.setOilName("98#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取97号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata20")
    public TableDataInfo listQydata20(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {
            Station station = new Station();
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }

        }
        payOrder.setOilName("-20#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取97号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata0")
    public TableDataInfo listQydata0(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        payOrder.setOilName("0#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取97号汽油数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listQydata10")
    public TableDataInfo listQydata10(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        payOrder.setOilName("-10#");
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.listQydata(payOrder);
        return getTable(orderList);
    }

    /**
     * 获取x轴数据
     *
     * @param payOrder
     * @return
     */
    @GetMapping("/listXdata")
    public TableDataInfo listXdata(PayOrder payOrder) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (stations != null && stations.size() > 0) {
                payOrder.setStationIdList(list);
            }


        } else if ("2".equals(current.getUser().getUserLevel())) {
            payOrder.setStationId(current.getUser().getStationId());
        } else {

        }
        //payOrder.setStatus("1");
        //payOrder.setOrderType("1");
        List<PayOrder> orderList = payOrderHistoryService.listXdata(payOrder);
        return getTable(orderList);
    }

    /**
     * 新增订单支付
     */
    @PostMapping
    public AjaxResult add(@RequestBody PayOrder payOrder) {
        return toAjax(payOrderHistoryService.insertPayOrder(payOrder));
    }

    /**
     * 修改订单支付
     */
    @PutMapping
    public AjaxResult edit(@RequestBody PayOrder payOrder) {
        return toAjax(payOrderHistoryService.updatePayOrder(payOrder));
    }

    /**
     * 删除订单支付
     */
    @DeleteMapping("/{orderIds}")
    @ApiOperation("批量删除")
    public AjaxResult remove(@PathVariable Long[] orderIds) {
        return toAjax(payOrderHistoryService.deletePayOrderByIds(orderIds));
    }

    /**
     * 批量删除订单
     * @return
     */
    @DeleteMapping("/deleteHistoryOrderPay")
    @ApiOperation("批量删除")
    public AjaxResult deletePay(@RequestBody Long[] orderIds){
        return toAjax(payOrderHistoryService.deletePayOrderByIds(orderIds));
    }



    /**
     * 查询订单的统计量
     */
    @GetMapping("/selectPayOrderSum")
    @ApiOperation("查询订单")
    public AjaxResult selectPayOrderSum(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        if (payOrder.getBeginTime() != "" && payOrder.getEndTime() != "") {
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate beginDate = LocalDate.parse(payOrder.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(payOrder.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                return AjaxResult.error("仅可查询一个月");
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate today = LocalDate.now(); // 当前日期
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            payOrder.setBeginTime(beginTimeStr);
            payOrder.setEndTime(endTimeStr);
        }
        log.info("selectPayOrderSum是否传了isDeleted:{}",payOrder.getIsDeleted());
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        if (StringUtils.equals(UserConstants.LEVEL_TWO,user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (CollectionUtils.isNotEmpty(list)) {
                payOrder.setStationIdList(list);
            }

        } else if (StringUtils.equals(UserConstants.LEVEL_THREE,user.getUserLevel())) {
            payOrder.setStationId(user.getStationId());

            if(StaffUtil.isStaff(user)){
                payOrder.setOilPersonnelId(String.valueOf(user.getUserId()));
            }else{
                Station station = stationService.selectStationById(current.getUser().getStationId());
                String showPayWayIds =  station.getShowPayWayIds();
                if (showPayWayIds!=null){
                    String[] idArray = showPayWayIds.split(","); // 拆分成字符串数组
                    List<Long> idList = new ArrayList<>();
                    for (int i = 0; i < idArray.length; i++) {
                        String id = idArray[i].trim();
                        if (!id.isEmpty()) {
                            idList.add(Long.parseLong(id));
                        }
                    }
                    payOrder.setPayWayIdList(idList);
                }
            }
        }
        payOrderController.assignPayOrder(payOrder,user);

        PayOrder sumPayOrder = payOrderHistoryService.selectSumPayOrder(payOrder);
        XcxActualPaymentDto xcxActualPayment = new XcxActualPaymentDto();
        xcxActualPayment.setEnterpriseId(user.getEnterpriseId());
        XcxActualPaymentDto resultXcx =    userService.xcxActualPaymentDetail(xcxActualPayment);

        if (StringUtils.equals(UserConstants.LEVEL_TWO,user.getUserLevel())) {
            sumPayOrder.setIsShowAmt(resultXcx.getIsEnterprise());
    } else if (StringUtils.equals(UserConstants.LEVEL_THREE,user.getUserLevel())) {
            if(StaffUtil.isStaff(user)){
                sumPayOrder.setIsShowAmt(resultXcx.getIsStaff());
            }else{
                sumPayOrder.setIsShowAmt(resultXcx.getIsStation());
            }
        }
        PayOrder sevenPayOrder = payOrderService.selectSumPayOrder(payOrder);
        if (sumPayOrder != null && sevenPayOrder != null) {
            sumPayOrder.setAmt((sumPayOrder.getAmt() != null ? sumPayOrder.getAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getAmt() != null ? sevenPayOrder.getAmt() : BigDecimal.ZERO));
            sumPayOrder.setCountNum(sumPayOrder.getCountNum() + sevenPayOrder.getCountNum());
            sumPayOrder.setCyAmt((sumPayOrder.getCyAmt() != null ? sumPayOrder.getCyAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getCyAmt() != null ? sevenPayOrder.getCyAmt() : BigDecimal.ZERO));
            sumPayOrder.setDiscountAmt((sumPayOrder.getDiscountAmt() != null ? sumPayOrder.getDiscountAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getDiscountAmt() != null ? sevenPayOrder.getDiscountAmt() : BigDecimal.ZERO));
            sumPayOrder.setOrderLiters((sumPayOrder.getOrderLiters() != null ? sumPayOrder.getOrderLiters() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getOrderLiters() != null ? sevenPayOrder.getOrderLiters() : BigDecimal.ZERO));
            sumPayOrder.setQyAmt((sumPayOrder.getQyAmt() != null ? sumPayOrder.getQyAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getQyAmt() != null ? sevenPayOrder.getQyAmt() : BigDecimal.ZERO));
            sumPayOrder.setReceivableAmt((sumPayOrder.getReceivableAmt() != null ? sumPayOrder.getReceivableAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getReceivableAmt() != null ? sevenPayOrder.getReceivableAmt() : BigDecimal.ZERO));
            sumPayOrder.setReceivedAmt((sumPayOrder.getReceivedAmt() != null ? sumPayOrder.getReceivedAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getReceivedAmt() != null ? sevenPayOrder.getReceivedAmt() : BigDecimal.ZERO));
            BigDecimal ssamt1 = new BigDecimal(sumPayOrder.getSsAmt() != null ? sumPayOrder.getSsAmt() : "0");
            BigDecimal ssamt2 = new BigDecimal(sevenPayOrder.getSsAmt() != null ? sevenPayOrder.getSsAmt() : "0");
            sumPayOrder.setSsAmt(ssamt1.add(ssamt2).toString());
            sumPayOrder.setDiscountCouponAmt((sumPayOrder.getDiscountCouponAmt() != null ? sumPayOrder.getDiscountCouponAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getDiscountCouponAmt() != null ? sevenPayOrder.getDiscountCouponAmt() : BigDecimal.ZERO));
            sumPayOrder.setAllPreferential((sumPayOrder.getDiscountAmt() != null ? sumPayOrder.getDiscountAmt() : BigDecimal.ZERO)
                    .add(sumPayOrder.getDiscountCouponAmt() != null ? sumPayOrder.getDiscountCouponAmt() : BigDecimal.ZERO));
        }

        return AjaxResult.success(sumPayOrder);
    }


    /**
     * 查询订单的统计量
     */
    @GetMapping("/selectPayOrderAndRechangeSum")
    @ApiOperation("查询订单和充值")
    public AjaxResult selectPayOrderAndRechangeSum(PayOrder payOrder) {
       /* List<String> list = deptService.levelDeptList(payOrder.getLevelId());
        if(list!=null && list.size()>0){
            payOrder.setStationIdList(list);
            payOrder.setStationId(null);
        }*/
        if (payOrder.getBeginTime() != "" && payOrder.getEndTime() != "") {
            // 将字符串转换为LocalDate类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate beginDate = LocalDate.parse(payOrder.getBeginTime(), formatter);
            LocalDate endDate = LocalDate.parse(payOrder.getEndTime(), formatter);

            // 计算两个日期之间的差值
            long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                return AjaxResult.error("查询时间不能大于一个月");
            }
        } else {
            // 开始时间和结束时间为空的逻辑
            LocalDate today = LocalDate.now(); // 当前日期
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

// 将开始时间和结束时间的字符串赋值给相应的变量
            payOrder.setBeginTime(beginTimeStr);
            payOrder.setEndTime(endTimeStr);
        }
        log.info("selectPayOrderSum是否传了isDeleted:{}",payOrder.getIsDeleted());
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();
        if (StringUtils.equals(UserConstants.LEVEL_TWO,user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            List<Station> stations = stationService.selectStationList(station);
            for (Station ss : stations) {
                list.add(ss.getStationId() + "");
            }
            if (CollectionUtils.isNotEmpty(list)) {
                payOrder.setStationIdList(list);
            }

        } else if (StringUtils.equals(UserConstants.LEVEL_THREE,user.getUserLevel())) {
            payOrder.setStationId(user.getStationId());
            if(StaffUtil.isStaff(user)){
                payOrder.setOilPersonnelId(String.valueOf(user.getUserId()));
            }
        }
        payOrderController.assignPayOrder(payOrder,user);

        PayOrder sumPayOrder = payOrderHistoryService.selectSumPayOrder(payOrder);
        PayOrder sevenPayOrder = payOrderService.selectSumPayOrder(payOrder);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("createStartTime", payOrder.getBeginTime());
        params.put("createEndTime", payOrder.getEndTime());
        params.put("stationId", payOrder.getStationId());
        params.put("payTypeList", payOrder.getRechargeTypeList());
        params.put("serviceType", "BGS");//班结的时候多维度分组查询
        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);
        CardClassSettDto settDto = classSettlementService.countCardSett(classSettlementCards); // 电子卡交易汇总数据
        ClassSettlementCard saleActivity = classSettlementService.forSaleActivity(params);
        BigDecimal saleActivityAmt = saleActivity.getAmt()!=null?saleActivity.getAmt():BigDecimal.ZERO;
        BigDecimal saleActivityCom = saleActivity.getServiceCharge()!=null?saleActivity.getServiceCharge():BigDecimal.ZERO;
        BigDecimal saleActivityWithdrawalAmount = saleActivity.getWithdrawalAmount()!=null?saleActivity.getWithdrawalAmount():BigDecimal.ZERO;




        if (sumPayOrder != null && sevenPayOrder != null) {
            sumPayOrder.setAmt((sumPayOrder.getAmt() != null ? sumPayOrder.getAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getAmt() != null ? sevenPayOrder.getAmt() : BigDecimal.ZERO));
            sumPayOrder.setAllPayAmt((sumPayOrder.getAllPayAmt() != null ? sumPayOrder.getAllPayAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getAllPayAmt() != null ? sevenPayOrder.getAllPayAmt() : BigDecimal.ZERO));
            sumPayOrder.setAllChannelAmt((sumPayOrder.getAllChannelAmt() != null ? sumPayOrder.getAllChannelAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getAllChannelAmt() != null ? sevenPayOrder.getAllChannelAmt() : BigDecimal.ZERO));
            sumPayOrder.setCountNum(sumPayOrder.getCountNum() + sevenPayOrder.getCountNum());
            sumPayOrder.setCyAmt((sumPayOrder.getCyAmt() != null ? sumPayOrder.getCyAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getCyAmt() != null ? sevenPayOrder.getCyAmt() : BigDecimal.ZERO));
            sumPayOrder.setDiscountAmt((sumPayOrder.getDiscountAmt() != null ? sumPayOrder.getDiscountAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getDiscountAmt() != null ? sevenPayOrder.getDiscountAmt() : BigDecimal.ZERO));
            sumPayOrder.setOrderLiters((sumPayOrder.getOrderLiters() != null ? sumPayOrder.getOrderLiters() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getOrderLiters() != null ? sevenPayOrder.getOrderLiters() : BigDecimal.ZERO));
            sumPayOrder.setQyAmt((sumPayOrder.getQyAmt() != null ? sumPayOrder.getQyAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getQyAmt() != null ? sevenPayOrder.getQyAmt() : BigDecimal.ZERO));
            sumPayOrder.setReceivableAmt((sumPayOrder.getReceivableAmt() != null ? sumPayOrder.getReceivableAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getReceivableAmt() != null ? sevenPayOrder.getReceivableAmt() : BigDecimal.ZERO));
            sumPayOrder.setReceivedAmt((sumPayOrder.getReceivedAmt() != null ? sumPayOrder.getReceivedAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getReceivedAmt() != null ? sevenPayOrder.getReceivedAmt() : BigDecimal.ZERO));
            sumPayOrder.setCommission((sumPayOrder.getCommission()!= null ? sumPayOrder.getCommission() : BigDecimal.ZERO)
             .add(sevenPayOrder.getCommission() != null ? sevenPayOrder.getCommission() : BigDecimal.ZERO));
            BigDecimal ssamt1 = new BigDecimal(sumPayOrder.getSsAmt() != null ? sumPayOrder.getSsAmt() : "0");
            BigDecimal ssamt2 = new BigDecimal(sevenPayOrder.getSsAmt() != null ? sevenPayOrder.getSsAmt() : "0");
            sumPayOrder.setSsAmt(ssamt1.add(ssamt2).toString());
            sumPayOrder.setDiscountCouponAmt((sumPayOrder.getDiscountCouponAmt() != null ? sumPayOrder.getDiscountCouponAmt() : BigDecimal.ZERO)
                    .add(sevenPayOrder.getDiscountCouponAmt() != null ? sevenPayOrder.getDiscountCouponAmt() : BigDecimal.ZERO));
            sumPayOrder.setAllPreferential((sumPayOrder.getDiscountAmt() != null ? sumPayOrder.getDiscountAmt() : BigDecimal.ZERO)
                    .add(sumPayOrder.getDiscountCouponAmt() != null ? sumPayOrder.getDiscountCouponAmt() : BigDecimal.ZERO));
        }
        if (payOrder.getRechargeType() == null||payOrder.getRechargeType().equals("")){
            sumPayOrder.setAllChannelAmt((sumPayOrder.getAllChannelAmt() != null ? sumPayOrder.getAllChannelAmt() : BigDecimal.ZERO)
                    .add( settDto.getTotalWxServiceCharge() != null ? settDto.getTotalWxServiceCharge() : BigDecimal.ZERO)
                    .add(settDto.getTotalPosServiceCharge() != null ? settDto.getTotalPosServiceCharge() : BigDecimal.ZERO));
            sumPayOrder.setRechargeAmt(settDto.getTotalAmt());

            sumPayOrder.setAllAccountAmt((sumPayOrder.getAllPayAmt() != null ? sumPayOrder.getAllPayAmt() : BigDecimal.ZERO)
                    .add( sumPayOrder.getRechargeAmt() != null ? sumPayOrder.getRechargeAmt() : BigDecimal.ZERO).subtract(sumPayOrder.getAllChannelAmt()));

        }else if(payOrder.getRechargeType().equals("wx")){
            sumPayOrder.setAllChannelAmt((sumPayOrder.getAllChannelAmt() != null ? sumPayOrder.getAllChannelAmt() : BigDecimal.ZERO)
                    .add( settDto.getTotalWxServiceCharge() != null ? settDto.getTotalWxServiceCharge() : BigDecimal.ZERO));
            sumPayOrder.setRechargeAmt(settDto.getWxAmt());

            sumPayOrder.setAllAccountAmt((sumPayOrder.getAllPayAmt() != null ? sumPayOrder.getAllPayAmt() : BigDecimal.ZERO)
                    .add( sumPayOrder.getRechargeAmt() != null ? sumPayOrder.getRechargeAmt() : BigDecimal.ZERO).subtract(sumPayOrder.getAllChannelAmt()));

        }else if(payOrder.getRechargeType().equals("pos")){
            sumPayOrder.setAllChannelAmt((sumPayOrder.getAllChannelAmt() != null ? sumPayOrder.getAllChannelAmt() : BigDecimal.ZERO)
                    .add( settDto.getTotalPosServiceCharge() != null ? settDto.getTotalPosServiceCharge() : BigDecimal.ZERO));
            sumPayOrder.setRechargeAmt(settDto.getPosAmt());
            sumPayOrder.setAllAccountAmt((sumPayOrder.getAllPayAmt() != null ? sumPayOrder.getAllPayAmt() : BigDecimal.ZERO)
                    .add( sumPayOrder.getRechargeAmt() != null ? sumPayOrder.getRechargeAmt() : BigDecimal.ZERO).subtract(sumPayOrder.getAllChannelAmt()));
        }
        sumPayOrder.setAllChannelAmt((sumPayOrder.getAllChannelAmt() != null ? sumPayOrder.getAllChannelAmt() : BigDecimal.ZERO).add(saleActivityCom));
        sumPayOrder.setSaleAmt(saleActivityAmt);
        BigDecimal allAccountAmt = (sumPayOrder.getAllPayAmt() != null ? sumPayOrder.getAllPayAmt() : BigDecimal.ZERO).add(saleActivityAmt)
                .add( sumPayOrder.getRechargeAmt() != null ? sumPayOrder.getRechargeAmt() : BigDecimal.ZERO).subtract(sumPayOrder.getAllChannelAmt());
        sumPayOrder.setAllAccountAmt(allAccountAmt);
               return AjaxResult.success(sumPayOrder);
    }


}
